/**
 * @author 曾海津
 */

let questionList = $("#question-list");
let tempData;
// 从本地存储获取问卷列表

// 初始化本地数据
function initial(status = -1) {
    tempData = getDataFromLocal("tempData");
    localStorage.setItem("tempId", status);
    const t = document.querySelector('#Template');
    let questionnaireListHtml = "";
    let tempQuestionnaireListHtml = "";
    tempData.forEach((item) => {
        let Template = t;
        Template.content.querySelectorAll('.btn-icon')[0].style.display = 'none';
        Template.content.querySelectorAll('.btn-icon')[1].style.display = 'none';
        Template.content.querySelectorAll('.btn-icon')[2].style.display = 'none';
        if (item.status === 0) {
            Template.content.querySelectorAll('.btn-icon')[0].style.display = 'inline';
        } else if (item.status === 1) {
            Template.content.querySelectorAll('.btn-icon')[1].style.display = 'inline';
            Template.content.querySelectorAll('.btn-icon')[2].style.display = 'inline';
        } else if (item.status === 2) {
            Template.content.querySelectorAll('.btn-icon')[2].style.display = 'inline';
        }
        Template.content.querySelector('td pre').innerHTML = item.title;
        Template.content.querySelector('.table-time').textContent = item.createTime;
        Template = Template.innerHTML.replaceAll('{id}', item.id);
        if (item.status === 0 && (status === -1 || status === item.status)) {
            tempQuestionnaireListHtml = Template.replace("{status}", "未发布")
                .replace("table-status", "table-status status-private");
            questionnaireListHtml += tempQuestionnaireListHtml;
        } else if (item.status === 1 && (status === -1 || status === item.status)) {
            tempQuestionnaireListHtml = Template.replace("{status}", "已发布")
                .replace("table-status", "table-status status-public");
            questionnaireListHtml += tempQuestionnaireListHtml;
        } else if (item.status === 2 && (status === -1 || status === item.status)) {
            tempQuestionnaireListHtml = Template.replace("{status}", "已结束")
                .replace("table-status", "table-status status-finished");
            questionnaireListHtml += tempQuestionnaireListHtml;
        }
    });
    questionList.innerHTML = questionnaireListHtml;
    $("#checkbox-choose-all").checked = false;
    checkboxListener();
}
initial();

// 根据id删除问卷
function delQuestionnaire(id) {
    let newList = delAnListItem(questionnaires, Number(id));

    if (newList.length === 0) {
        location.href = "new.html";
    }
    questionnaires = deepClone(newList);
    saveDataToLocal(questionnaires, "questionnaires");
    initial();
}

// 删除和编辑
questionList.addEventListener("click", function (e) {
    let event = e.target;
    let operationType = event.getAttribute("data-type") ? event.getAttribute("data-type") : event.parentElement.getAttribute("data-type");
    let questionnaireId = event.getAttribute("data-type") ? event.parentElement.getAttribute("data-id") : event.parentElement.parentElement.getAttribute("data-id");
    // 删除问卷
    if (operationType === "operation-del") {
        myConfirm("你确定要删除这份问卷吗？", () => {
            delQuestionnaire(questionnaireId);
            location.href="index.html";
        });
    }
    // 编辑问卷
    if (operationType === "operation-edit") {
        myConfirm("你确定要编辑这份问卷吗？", () => {
            location.href = "edit.html?id=" + questionnaireId;
        });
    }
    // 填写问卷
    if (operationType === "operation-write") {
        myConfirm("你确定要填写这份问卷吗？", () => {
            location.href = "write.html?id=" + questionnaireId;
        });
    }
    // 查看数据
    if (operationType === "operation-view") {
        myConfirm("你确定要查看这份问卷吗？", () => {
            location.href = "view.html?id=" + questionnaireId;
        });
    }
});

// 批量删除
$("#btn-multi-delete").onclick = () => {
    let checkboxes = Array.from($(".choose-checkbox"));
    let delList = [];
    let newList = [];
    checkboxes.forEach(item => {
        if (item.checked) {
            delList.push(Number(item.getAttribute("data-id")));
        }
    });
    if (delList.length === 0) {
        message("没有选择要删除的问卷！");
        return;
    }
    document.querySelector('#btn-multi-delete').style.display = 'none';
    const confirmDelete = document.querySelector('#btn-confirm-delete');
    confirmDelete.style.display = 'block';
    const timeout = setTimeout(() => {
        document.querySelector('#btn-multi-delete').style.display = 'block';
        confirmDelete.style.display = 'none';
        message("取消删除");
    }, 1500);
    confirmDelete.onclick = () => {
        clearTimeout(timeout);
        document.querySelector('#btn-multi-delete').style.display = 'block';
        confirmDelete.style.display = 'none';
        delList.forEach(item => {
            questionnaires[item - 1] = {};
        });
        let i = 1;
        questionnaires.forEach(item => {
            if (item.id !== undefined) {
                item.id = i;
                newList.push(item);
                i++;
            }
        });
        if (newList.length === 0) {
            questionnaires = [];
            saveDataToLocal(questionnaires, "questionnaires");
            location.href = "new.html";
            return;
        }
        questionnaires = deepClone(newList);
        saveDataToLocal(questionnaires, "questionnaires");
        message("删除成功！");
        location.href="index.html";
    }
};

$("#table-choose").addEventListener("click", (e) => {
    if (e.target.type === "checkbox") {
        if (e.target.checked === true) {
            Array.from($(".choose-checkbox")).forEach(item => {
                item.checked = true;
            });
        } else {
            Array.from($(".choose-checkbox")).forEach(item => {
                item.checked = false;
            });
        }
    }
});
//问卷项目全选时上方全选打勾
function checkboxListener() {
    Array.from(document.querySelectorAll(".checkbox-choose")).forEach(item => {
        item.addEventListener("click", (e) => {
            let flag = 1;
            if (e.target.type === "checkbox") {
                Array.from(document.querySelectorAll(".choose-checkbox")).forEach(item => {
                    if (item.checked !== true) {
                        flag = 0;
                    }
                });
                if (flag === 1) {
                    document.querySelector('#checkbox-choose-all').checked = true;
                } else {
                    document.querySelector('#checkbox-choose-all').checked = false;
                }
            }
        });
    })
}


//状态筛选功能
document.querySelector('#table-status').addEventListener("click", (e) => {
    if (e.target.className === "status-item") {
        let id = e.target.getAttribute("data-id");
        initial(Number(id));
        let template = document.querySelector("#status-template").innerHTML;
        let newHtml = "";
        switch (id) {
            case ('0'):
                newHtml = template.replace("{status}", "未发布");
                break;
            case ('1'):
                newHtml = template.replace("{status}", "已发布");
                break;
            case ('2'):
                newHtml = template.replace("{status}", "已结束");
                break;
            default:
                newHtml = template.replace("{status}", "状态");
        }
        document.querySelector('#table-status').innerHTML = newHtml;
        decPageIndex(getDataFromLocal("questionnaires"), 1, 1, id);
    }
});

headerAnimation();
